<?php
namespace plugins\appmarket\controller;
use cmf\controller\PluginAdminBaseController;//引入此类
use plugins\appmarket\model\DownloadHostAddress;
use think\Controller;
/**
 * 应用市场配置控制器 
 */
class ConfigController extends PluginAdminBaseController
{	
	/**
	 * 模块资源文件下载地址配置
	 *
	 *appmarket.json 配置文件名称
	 *配置内容结构:
	 *	主机下载地址：
	 *	[
	 *		'downloadHostAddress'	=> [
	 *			'main' => [
	 *				'address'   => '主地址',
	 *				'status'	=> '状态：开/关'
	 *			],
	 *			'minor' => [
	 *				'address'   => '副地址',
	 *				'status'	=> '状态：开/关'
	 *			],
	 *		]
	 *  ]
	 *
	 * @adminMenu(
     *     'name'   => '常规配置',
     *     'parent' => 'AdminIndex/index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '常规配置',
     *     'param'  => ''
     * )
	 */
	public function index()
	{
		if( $this->request->isPost() ){
			//保存数据
			$data = $this->request->param();
			$content = $this->setDownloadHostAddress( $data );
			//保存数据
			try {
				self::saveConfigData($content);
			} catch (\Exception $e) {
				$this->error( $e->getMessage () );
			}
			$this->success( '保存成功！' );
		}else{
			//显示数据
			$content = self::getConfigData();
			if( empty( $content ) ) $content = $this->setDownloadHostAddress( );
			$address =  $content [ 'minor' ] ;
			$mainAddress = $content [ 'main' ] ;
			$this->assign( 'address' , $address );
			$this->assign( 'mainAddress' , $mainAddress );
			return $this->fetch( 'config/index' );
		}
	}

	/**
	 * [setDownloadHostAddress description]
	 */
	private  function setDownloadHostAddress( $data = [] )
	{
		$newData = [
			'main' =>[
				'address' 	=> isset( $data [ 'mainAddress' ] ) ? $data [ 'mainAddress' ] : '' ,
				'status'	=> isset( $data [ 'mainStatus' ] ) ? $data [ 'mainStatus' ] : 0 
			],
			'minor'	=>[
				'address' 	=> isset( $data [ 'address' ] ) ? $data [ 'address' ] : '' ,
				'status'	=> isset( $data [ 'status' ] ) ? $data [ 'status' ] : '' 
			]
		];
		return $newData ;
	}	

	/**
	 * 读取配置文件
	 */
	public static function getConfigData( )
	{
		$content = getModuleConfig( 'appmarket' , 'config' , 'appmarket.json');
		$content = json_decode( $content, true );
		if( empty( $content ) ){
			return [];
		}
		return $content;
	} 
	/**
	 * 保存配置文件
	 * @adminMenu(
     *     'name'   => '配置提交',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '配置提交',
     *     'param'  => ''
     * )
	 */
	public static function saveConfigData( $data =  [] )
	{
		$res = saveModuleConfigData( "appmarket" , "config" , "appmarket.json" , $data ) ;
		return $res;
	}

	/**
	 * 获取资源文件下载主机地址
	 */
	public static function getDownloadHostAddress()
	{
		$content = self::getConfigData();

		if( empty( $content ) ) $content = $this->setDownloadHostAddress(); 
		return $content;
	}
}
